package com.ruoyi.web.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.itextpdf.local.ess.Revision.RevisionUtils;
import com.itextpdf.local.ess.verify.VerifyPdfUtil;
import com.itextpdf.local.ess.verify.VerifySignInfo;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.*;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.service.*;
import com.ruoyi.web.bean.PDFPage;
import com.ruoyi.web.dto.SealDto;
import com.ruoyi.web.service.*;
import com.ruoyi.web.util.OAWebService.hnzy.Exception_Exception;
import com.ruoyi.web.util.OAWebService.hnzy.IZyEssWebserviceService;
import com.ruoyi.web.util.OAWebService.hnzy.IZyEssWebserviceServiceService;
import com.ruoyi.web.util.OAWebService.hnzy.ZyEssParamterForm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import static com.itextpdf.local.ess.FileUtils.File2byte;
import static com.ruoyi.common.utils.Base64Utils.ESSGetBase64Decode;
import static com.ruoyi.common.utils.Base64Utils.ESSGetBase64Encode;
import static com.ruoyi.common.utils.StringUtils.isNull;
import static com.ruoyi.common.utils.file.FileUtils.byte2Input;
import static com.ruoyi.web.util.pdf.PdfUtils.convertCoordinate;
import static org.apache.commons.lang3.StringUtils.indexOf;

/**
 * 重庆烟草签章实现
 * 异步签章
 * 签章接口需要业务系统提供回调方式
 */
@Controller
@Slf4j
@RequestMapping(value="/pdf")
public class PdfSignController {

    @Autowired
    private CQYCSignService signService;
    @Autowired
    private IBusinessSysService businessSysService;
    @Autowired
    private IPersonService personService;
    @Autowired
    private IDockingErrService dockingErrService;
    @Resource
    private AsyncSignService asyncSignService;
    @Resource
    private IWebSignService webService;
    @Resource
    private SealService sealService;
    @Resource
    private FileService fileService;
    @Resource
    private ISealJurService sealJurService;
    @Resource
    private IPdfTokenService pdfTokenService;

    /**
     * 根据关键字定位对pdf进行签章
     * @param data 签章数据
     * @return 返回结果
     */
    @RequestMapping(value ="/signPdfByKeyword")
    @ResponseBody
    public String signPdfByKeyword(String data,HttpServletRequest request) {
        return signPdf(data,request);
    }
    /**
     * 根据书签定位对pdf进行签章
     * @param data 签章数据
     * @return 返回结果
     */
    @RequestMapping(value ="/signPdfByBookmark")
    @ResponseBody
    public String signPdfByBookmark(String data,HttpServletRequest request) {
        return signPdf(data,request);
    }
    /**
     * 根据坐标定位对pdf进行签章
     * @param data 签章数据
     * @return 返回结果
     */
    @RequestMapping(value ="/signPdfByXY")
    @ResponseBody
    public String signPdfByXY(String data,HttpServletRequest request) {
        return signPdf(data,request);
    }
    /**
     * 骑缝章
     * @param data 签章数据
     * @return 返回结果
     */
    @RequestMapping(value ="/signPdfByOver")
    @ResponseBody
    public String signPdfByOver(String data,HttpServletRequest request) {
        return signPdf(data,request);
    }
    /**
     * 对签章前置参数进行检查
     * @param businessSys 业务系统ID
     * @param signUser 签章人
     * @param documentCode 文档编码
     * @return  检查结果
     */
    public JSONObject ParameterCheck(String businessSys, String signUser,String documentCode){
        JSONObject result = new JSONObject();
        //查找业务系统名称
        BusinessSys business_system  = businessSysService.selectBusinessSysByBSysId(businessSys);
        if (business_system==null){
            result.put("code","0002");
            result.put("msg","找不到业务系统");
            return result;
        }
        //查找签章人员
        Person signPer = personService.findPersonBySYS(businessSys,signUser);
        if (signPer==null){
            result.put("code","0001");
            result.put("msg","找不到签章人");
            return result;
        }
        result.put("code","0000");
        result.put("msg","参数检查通过");
        return result;
    }
    /**
     * 对接收的参数做一次补全，目的是支持两种参数形式
     * Content-Type: application/x-www-form-urlencoded  参数正文
     * Content-Type: application/json 文本正文
     * @return 参数
     */
    public String complementParam(String data,HttpServletRequest request){
        if (data ==null){
            StringBuilder data1 = new StringBuilder();
            String line ;
            BufferedReader reader ;
            try {
                reader = request.getReader();
                while (null != (line = reader.readLine())) {
                    data1.append(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            data = data1.toString();
        }
        return data;
    }
    /**
     * PDF文档验章接口，接口
     */
    @RequestMapping(value ="/verify")
    @ResponseBody
    public VerifySignInfo verify(MultipartFile document) throws Exception {
        List<byte[]> certs = new ArrayList<>();
//        certs.add(File2byte("D:/pdf/rootjs.cer"));
        //获取原始文件名称
//        String originalFilename = document.getOriginalFilename();
//        VerifySignInfo verify = VerifyPdfUtil.verify(FileUtils.inputStream2byte(document.getInputStream()),certs);
        VerifySignInfo verify = VerifyPdfUtil.verify(FileUtils.File2byte("d:\\demo.pdf"),certs);
//        verify.setName(originalFilename);
        return verify;
    }

    /**
     * PDF文档验章接口，接口
     */
    @RequestMapping(value ="/v1/extractRevision")
    @ResponseBody
    public String extractRevisionV1(@RequestBody JSONObject data) throws Exception {
        JSONObject result = new JSONObject();
//        //检查参数
        String documentCode;
        String signatureName;
        if (data.containsKey("documentCode")&&data.containsKey("signatureName")){
            documentCode = data.getString("documentCode");
            signatureName = data.getString("signatureName");
        }else {
            result.put("code","w0001");
            result.put("msg","参数类型不全");
            return result.toJSONString();
        }
        byte[] file = fileService.downloadDocument(documentCode,Constants.SIGN_PDF_SUFFIX);
        byte[] newFile = RevisionUtils.switchToRevision(file,signatureName);
        if (newFile==null){
            result.put("code","0002");
            result.put("msg","回退时出错");
            return result.toJSONString();
        }
        //签章成功后，将签章后的文件作为新文件保存生成新的code
        String documentCodeNew = IdUtils.simpleUUID();
        PdfDocument pdf = new PdfDocument();
        pdf.setDocumenttype("pdf");
        pdf.setDocumentcode(documentCodeNew);
        pdf.setDocumentname(documentCodeNew);
        fileService.addPdfDocument(pdf);
        fileService.saveDocument(
                byte2Input(newFile),documentCodeNew,Constants.SIGN_PDF_SUFFIX);
        result.put("code","0000");
        result.put("msg","回退成功");
        result.put("data",documentCodeNew);
        return result.toJSONString();
    }


    /**
     * PDF文档验章接口，接口
     */
    @RequestMapping(value ="/extractRevision")
    @ResponseBody
    public String extractRevision(@RequestBody JSONObject data) throws Exception {
        JSONObject result = new JSONObject();
//        //检查参数
        String document;
        String signatureName;
        if (data.containsKey("document")&&data.containsKey("signatureName")){
            document = data.getString("document");
            signatureName = data.getString("signatureName");
        }else {
            result.put("code","0001");
            result.put("msg","参数类型不全");
            return result.toJSONString();
        }
        byte[] file = ESSGetBase64Decode(document);
        byte[] newFile = RevisionUtils.switchToRevision(file,signatureName);
        if (newFile==null){
            result.put("code","0002");
            result.put("msg","回退时出错");
            return result.toJSONString();
        }
        result.put("code","0000");
        result.put("msg","回退成功");
        result.put("data",ESSGetBase64Encode(newFile));
        return result.toJSONString();
    }


    /**
     * PDF文档验章接口，接口
     */
    @RequestMapping(value ="/v2/extractRevision")
    @ResponseBody
    public String extractRevisionV2(@RequestBody JSONObject data) throws Exception {
        JSONObject result = new JSONObject();
//        //检查参数
        String document;
        String userId;
        if (data.containsKey("document")&&data.containsKey("userId")){
            document = data.getString("document");
            userId = data.getString("userId");
        }else {
            result.put("code","0001");
            result.put("msg","参数类型不全");
            return result.toJSONString();
        }
        byte[] pdfFile = ESSGetBase64Decode(document);
        VerifySignInfo verify = VerifyPdfUtil.verifyWithoutImg(pdfFile);
        List<VerifySignInfo.SignatureDetail> signatureDetailList = verify.getSignatureDetails();
        if(!(signatureDetailList.size()>=1)){
            result.put("code","0001");
            result.put("msg","文档内没有签章");
            return result.toJSONString();
        }
        //将文档回退至空白签章状态
        pdfFile = RevisionUtils.switchToRevision(pdfFile,signatureDetailList.get(0).name);

        Iterator<VerifySignInfo.SignatureDetail> it = signatureDetailList.iterator();
        while(it.hasNext()){
            VerifySignInfo.SignatureDetail x = it.next();
            String signName = x.getName();
            String[] aa = signName.split("@");
            String user = aa[1];
            if (user.equals(userId)){
                it.remove();
            }
        }
        //遍历出所有印章
        for (VerifySignInfo.SignatureDetail signatureDetails: signatureDetailList) {
            JSONObject js1 = new JSONObject();
            String signName = signatureDetails.getName();
            String[] aa = signName.split("@");
            String sealId = aa[0];
            String user = aa[1];
            JSONArray ja = new JSONArray();
            //2022-05-12T15:11:41.000+08:00
            Date time = signatureDetails.getTime();
            int pageNum = signatureDetails.getPage();
            float Llx = signatureDetails.getLlx();
            float Lly = signatureDetails.getLly();
            float Urx = signatureDetails.getUrx();
            float Ury = signatureDetails.getUry();
            js1.put("sealId",sealId);
            js1.put("pageNum",pageNum);
            js1.put("X",(Llx+Urx)/2);
            js1.put("Y",(Lly+Ury)/2);
            js1.put("signTime",time);
            ja.add(js1);

            pdfFile = signService.signPDF(ja,pdfFile,"SYS001",user);
            if(pdfFile == null){
                result.put("code","0001");
                result.put("msg","回退过程中重新签章失败");
                return result.toJSONString();
            }
        }
        result.put("code","0000");
        result.put("msg","回退成功");
        result.put("data",ESSGetBase64Encode(pdfFile));
        return result.toJSONString();
    }


    /**
     * 集合定位 签章
     * @param data 签章数据
     * @return 返回结果
     */
    @RequestMapping(value ="/signPdf")
    @ResponseBody
    public String signPdf(String data,HttpServletRequest request){
        data = complementParam(data,request);
        JSONObject result;
        //首先确认参数
        JSONObject dataJs = null;
        try{
            dataJs = JSONObject.parseObject(data);
        }catch (Exception e){
            result = new JSONObject();
            result.put("code","0001");
            result.put("msg","参数格式异常");
            return result.toJSONString();
        }
        String documentCode = dataJs.getString("documentCode");
        String signUser = dataJs.getString("signUser");
        String businessSys = dataJs.getString("businessSys");
        //默认异步调用
        boolean isAsync = false;
        if (dataJs.containsKey("isAsync")){
            isAsync = dataJs.getBoolean("isAsync");
        }
        JSONArray seals =dataJs.getJSONArray("seals");
        //检查前置参数
        result = ParameterCheck(businessSys,signUser,documentCode);
        if (!result.getString("code").equals("0000")){
            //如果签章失败添加错误日志
            dockingErrService.insertDockingErrSign(businessSys,
                    result.getString("msg")+"&code:"+result.getString("code"),"异步签章");
            return result.toJSONString();
        }
        String event ="同步签章";
        if(isAsync){
            //异步签章
            asyncSignService.asyncSignPDF(seals,documentCode,businessSys,signUser);
            result.put("code","0000");
            result.put("msg","签章任务添加成功");
            event = "异步签章";
        }else {
            //同步签章
            result = signService.signPDF(seals,documentCode,businessSys,signUser);
        }
        if (!"0000".equals(result.getString("code"))){     //查找文档
            //如果签章失败添加错误日志
            dockingErrService.insertDockingErrSign(businessSys,
                    result.getString("msg")+"&code:"+result.getString("code"),event);
        }
        return result.toJSONString();
    }
    /**
     * 根据UserToken获取可用印章列表。
     *参数示例
     *     {"signToken":"634e33ad3ea6475cb6c89c1e783130b8","imgType":"1"}
     *     结果示例
     *     {
     *     "msg": [
     *                 {
     *                 "sealName": "余建华",
     *                 "hashA": "SM3",
     *                 "signA": "SM2",
     *                 "sealId": "039ad7fe963a449da49d204154cf77f2",
     *                 "isUK": "0",
     *                 "sealStruct": "国办标准",
     *                 "imgType": "gif"
     *                 },
     *                 {
     *                 "sealName": "刘大富",
     *                 "hashA": "SM3",
     *                 "signA": "SM2",
     *                 "sealId": "022e9c4f36c04c928cd264a62966aed1",
     *                 "isUK": "0",
     *                 "sealStruct": "安可标准",
     *                 "imgType": "gif"
     *                 }
     *             ],
     *     "code": "w0000"
     *     }
     * @return JSON字符串
     */
    @RequestMapping(value ="/getSealListBySignToken")
    @ResponseBody
    public String getSealListByUserToken(@RequestBody JSONObject jsonObject) {
        JSONObject result = new JSONObject();
        //检查参数
        String signToken ;
        String imgType ;
        if (jsonObject.containsKey("signToken")){
            signToken = jsonObject.getString("signToken");
            imgType = jsonObject.getString("imgType");
            if ("1".equals(imgType)){
                imgType = "gif";
            }else if ("2".equals(imgType)){
                imgType = "wacom";
            }
        }else {
            result.put("code","w0001");
            result.put("msg","参数类型不全");
            return result.toJSONString();
        }
        JSONArray msgJsonA = new JSONArray();
        //根据单位和部门查找印章列表
        PdfToken pdfToken = pdfTokenService.selectPdfTokenByTokenId(signToken);
        JSONArray jsonArray = JSONArray.parseArray(pdfToken.getSealList());
        for (Object o : jsonArray) {
            JSONObject sealJson = new JSONObject();
            //查找印章
            SealDto seal = sealService.findSealById((String) o);
            if (imgType.equals(seal.getSeal_img_type())){
                sealJson.put("sealName",seal.getSealName());
                sealJson.put("phoneNumber","");
                sealJson.put("sealId",seal.getSealId());
                sealJson.put("imgType",seal.getSeal_img_type());
                String sealStandard = seal.getSeal_standard();
                if(sealStandard.equals("1") || sealStandard.equals("2") || sealStandard.equals("3")){
                    sealJson.put("hashA","SM3");
//                    sealJson.put("signA","SM2");
                }else {
                    sealJson.put("hashA","SHA1");
//                    sealJson.put("signA","RSA");
                }
                if(sealStandard.equals("1") || sealStandard.equals("2") || sealStandard.equals("4")){
                    sealJson.put("isUK","1");
                }else {
                    sealJson.put("isUK","0");
                }
                if(sealStandard.equals("4") || sealStandard.equals("5") || sealStandard.equals("6")){
                    sealJson.put("sealStruct","公司自定义标准");
                }else if(sealStandard.equals("1") || sealStandard.equals("3") ){
                    sealJson.put("sealStruct","安可标准");
                }else if(sealStandard.equals("2")){
                    sealJson.put("sealStruct","国办标准");
                }
                msgJsonA.add(sealJson);
            }
        }
        result.put("code","w0000");
        result.put("msg",msgJsonA);
        return result.toJSONString();
    }
    /**
     * 根据UserToken获取可用印章列表。
     *参数示例
     *     {"signToken":"634e33ad3ea6475cb6c89c1e783130b8","sealId":"1"}
     *     结果示例
     *     {
     *          "msg": {
     *             "imgBase64 ": "",
     *             "imgWidth ": "",
     *             "imgHeight ": "",
     *             "imgType": ""
     *             }
     *          "code": "w0000"
     *      }
     *
     * @return JSON字符串
     */
    @RequestMapping(value ="/getSealImgBySealId")
    @ResponseBody
    public String getSealImgBySealId(@RequestBody JSONObject jsonObject) {
        JSONObject result = new JSONObject();
        //检查参数
        String signToken ;
        String sealId ;
        if (jsonObject.containsKey("signToken")){
            signToken = jsonObject.getString("signToken");
            sealId = jsonObject.getString("sealId");
        }else {
            result.put("code","w0001");
            result.put("msg","参数类型不全");
            return result.toJSONString();
        }
        JSONObject sealJson = new JSONObject();
        //查找印章
        SealDto seal = sealService.findSealById(sealId);
        if (!isNull(seal)){
            sealJson.put("imgType",seal.getSeal_img_type());
            sealJson.put("imgBase64",seal.getSeal_img());
            sealJson.put("imgWidth",seal.getSeal_w());
            sealJson.put("imgHeight",seal.getSeal_h());
            result.put("code","w0000");
            result.put("msg",sealJson);
            return result.toJSONString();
        }
        result.put("code","w0002");
        result.put("msg","未找到符合要求的数据");
        return result.toJSONString();
    }

    /**
     *     参数
     *         {
     *             "sysId":"SYS001",
     *             "userId":"00000189",
     *             "documentCode":"xxxxx"
     *         }
     *     返回结果
     *         {"msg":"xxxxx","code":"0000"}
     * @param data
     * @return
     */
    @RequestMapping(value="/getSignToken")
    @ResponseBody
    public String getSignToken(@RequestBody JSONObject data) {
        JSONObject result = new JSONObject();
//        //检查参数
        String sysId;
        String userId;
        String documentCode;
        if (data.containsKey("sysId")&&data.containsKey("userId")){
            sysId = data.getString("sysId");
            userId = data.getString("userId");
            documentCode = data.getString("documentCode");
        }else {
            result.put("code","w0001");
            result.put("msg","参数类型不全");
            return result.toJSONString();
        }
        String url = "-";
        String attId = "-";
        String userName = "-";
        String infoId = "-";
        if (data.containsKey("attId")){
            attId = data.getString("attId");
        }
        if (data.containsKey("url")){
            if (!"".equals(data.getString("url"))){
                url = data.getString("url");
            }
        }
        if (data.containsKey("userName")){
            userName = data.getString("userName");
        }
        if (data.containsKey("infoId")){
            if (!"".equals(data.getString("infoId"))){
                infoId = data.getString("infoId");
            }
        }
        //根据业务系统和人员查找授权列表
        List<SealJur> sealJurs = sealJurService.selectAllSealJurByUserId(userId,sysId);
        List<SealDto> sealList = new ArrayList<>();
        for (SealJur s:sealJurs) {
            SealDto sealDto = sealService.findSealById(s.getSealId());
            if(!isNull(sealDto)){
                sealList.add(sealDto);
            }
        }
        if (sealList.size() == 0){
            result.put("code","w0002");
            result.put("msg","用户ID错误或未查到授权印章");
            return result.toJSONString();
        }
        JSONArray ja = new JSONArray();
        for (SealDto sealDto: sealList) {
            ja.add(sealDto.getSealId());
        }
        PdfToken pdfToken = new PdfToken();
        pdfToken.setTokenId(IdUtils.simpleUUID());
        pdfToken.setSysId(sysId);
        pdfToken.setUserId(userId);
        pdfToken.setDocumentId(documentCode);
        pdfToken.setSealList(ja.toJSONString());
        pdfToken.setState(1);
        pdfToken.setInputTime(DateUtils.getTime());
        pdfToken.setAtt(attId+"@"+url+"@"+userName+"@"+infoId+"@");
        int res = pdfTokenService.insertPdfToken(pdfToken);
        //将data数据存入数据库中，
        result.put("code","w0000");
        result.put("msg",pdfToken.getTokenId());
        return result.toJSONString();
    }
    /**
     * 根据token 获取文档页面
     * @param data 数据
     * @throws IOException 异常
     *
     * 参数
     * {"signToken":"xxxxx","pageNum":"x"}
     *
     * 返回结果
     * {"pageImge":"图片base64数据","pageWidth":"x","pageHight":"x,"pageNumTotal":"x"}
     */
    @RequestMapping(value="/getDocumentPage")
    @ResponseBody
    public String getDocumentPage(@RequestBody JSONObject data){
        JSONObject result = new JSONObject();
        String signToken;
        int pageNum;
        if (data.containsKey("signToken")&&data.containsKey("pageNum")){
            signToken = data.getString("signToken");
            pageNum = data.getInteger("pageNum");
            //根绝token获取文档ID取得PDF文件
            PdfToken pdfToken = pdfTokenService.selectPdfTokenByTokenId(signToken);
            if (!isNull(pdfToken)){
                String documentCode = pdfToken.getDocumentId();
                byte[] pdfByte = fileService.downloadDocument(documentCode,"pdf");
                PDFPage pdfPage= fileService.getPDFPage(pdfByte,pageNum,96);
                if (isNull(pdfPage)){
                    result.put("code","w0004");
                    result.put("msg","文档页数错误");
                    return result.toJSONString();
                }
                result.put("code","w0000");
                result.put("msg","获取成功");
                JSONObject jsonObject = new JSONObject();
//                jsonObject.put("pageImge",pdfPage.getImageBase64());
                jsonObject.put("pageWidth",pdfPage.getWidth());
                jsonObject.put("pageHight",pdfPage.getHeight());
                jsonObject.put("pageNumTotal",pdfPage.getTolNum());
                result.put("data",jsonObject);
                return result.toJSONString();
            }else{
                result.put("code","w0003");
                result.put("msg","文档为空");
                return result.toJSONString();
            }
        }else{
            //参数格式错误
            result.put("code","w0002");
            result.put("msg","未找到符合要求的数据");
            return result.toJSONString();
        }
    }
    @RequestMapping(value="/getDocumentPageImg")
    @ResponseBody
    public void getDocumentPageImg(String token,int pageNum,HttpServletResponse response){
        //根绝token获取文档ID取得PDF文件
        PdfToken pdfToken = pdfTokenService.selectPdfTokenByTokenId(token);
        if (!isNull(pdfToken)) {
            String documentCode = pdfToken.getDocumentId();
            byte[] pdfByte = fileService.downloadDocument(documentCode, "pdf");
            PDFPage pdfPage = fileService.getPDFPageImg(pdfByte, pageNum, 96);
            try {
                byte[] bytes = ESSGetBase64Decode(pdfPage.getImageBase64());
                //设置MIME类型
                response.setContentType("image/gif");
                //设置头信息,设置文件下载时的默认文件名，同时解决中文名乱码问题
                response.addHeader("Content-disposition", "attachment;filename=" + token+".gif");
                //将文件流输出
                ServletOutputStream outputStream = response.getOutputStream();
                InputStream inputStream = FileUtils.byte2Input(bytes);
                int ch;
                while ((ch = inputStream.read()) != -1) {
                    outputStream.write(ch);
                }
                outputStream.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * @param data
     * @return
     * @throws Exception
     */
    @RequestMapping(value ="/dragSign")
    @ResponseBody
    public String dragSign(@RequestBody JSONObject data) {
        String signToken = "";
        JSONArray seals = new JSONArray();
//        String verifyUUID = "";
        JSONObject result = new JSONObject();
        if (data.containsKey("signToken")&&data.containsKey("seals")){
            signToken = data.getString("signToken");
            seals =data.getJSONArray("seals");
//            verifyUUID = data.getString("verifyUUID");
        }
//        if (!pdfTokenService.checkVerifyUUID(signToken,verifyUUID)){
//            result.put("code","w0005");
//            result.put("msg","当前操作未验证，请先验证");
//            return result.toJSONString();
//        }
        PdfToken pd = pdfTokenService.selectPdfTokenByTokenId(signToken);
        for (int i =0;i<seals.size();i++){
            JSONObject sealJson = seals.getJSONObject(i);
            //页面图像签章
            float X  = sealJson.getFloat("X");
            float Y  = sealJson.getFloat("Y");
            sealJson.put("X",convertCoordinate(X));
            sealJson.put("Y",convertCoordinate(Y));
        }
        //完成签章
        result = signService.signPDF(seals,pd.getDocumentId(),pd.getSysId(),pd.getUserId());
        if (!"0000".equals(result.getString("code"))){
            //如果签章失败添加错误日志
            dockingErrService.insertDockingErrSign(pd.getSysId(),
                    result.getString("msg")+"&code:"+result.getString("code"),"异步签章");
            return "error";
        }
        //业务系统签章成功的回写函数  重庆中烟项目
//        boolean aa = signService.sendSuccess("",documentCode);
        return result.toJSONString();
    }
    /** 湖南中烟
     * @param data
     * @return
     * @throws Exception
     */
//    @RequestMapping(value ="/dragSignMobile")
    @RequestMapping(value ="/dragSign/dragSignMobile")
    @ResponseBody
    public String dragSignMobile(@RequestBody JSONObject data) {
        String signToken = "";
        JSONArray seals = new JSONArray();
        JSONObject result;
        if (data.containsKey("signToken")&&data.containsKey("seals")){
            signToken = data.getString("signToken");
            seals =data.getJSONArray("seals");
        }
        PdfToken pd = pdfTokenService.selectPdfTokenByTokenId(signToken);
        for (int i =0;i<seals.size();i++){
            JSONObject sealJson = seals.getJSONObject(i);
            //页面图像签章
            float X  = sealJson.getFloat("X");
            float Y  = sealJson.getFloat("Y");
            sealJson.put("X",convertCoordinate(X));
            sealJson.put("Y",convertCoordinate(Y));
        }
        //完成签章
        result = signService.signPDF(seals,pd.getDocumentId(),pd.getSysId(),pd.getUserId());
        if (!"0000".equals(result.getString("code"))){
            //如果签章失败添加错误日志
            dockingErrService.insertDockingErrSign(pd.getSysId(),
                    result.getString("msg")+"&code:"+result.getString("code"),"异步签章");
            return "error";
        }
        String[] att = pd.getAtt().split("@");
        String attId = att[0];
        String url = att[1];
        String userName = att[2];
        String infoId = att[3];
        if ("-".equals(attId)){
            attId = "";
        }
        if ("-".equals(url)){
            url = "";
        }
        if ("-".equals(userName)){
            userName = "";
        }
        if ("-".equals(infoId)){
            infoId = "";
        }
        String documentCode = result.getString("msg");
        byte[] attFile = fileService.downloadDocument(documentCode,Constants.SIGN_PDF_SUFFIX);
        IZyEssWebserviceServiceService izService = new IZyEssWebserviceServiceService();
        IZyEssWebserviceService methodEx = izService.getIZyEssWebserviceServicePort();
        ZyEssParamterForm zyEssParamterForm = new ZyEssParamterForm();
        zyEssParamterForm.setAttId(attId);
        log.info("attId:"+attId);
        zyEssParamterForm.setAttFile(attFile);
        zyEssParamterForm.setFileName(documentCode+"."+Constants.SIGN_PDF_SUFFIX);
        log.info("fileName:"+documentCode+"."+Constants.SIGN_PDF_SUFFIX);
        zyEssParamterForm.setUserName(userName);
        System.out.println("userName:"+userName);
        log.info("userName:"+userName);
        zyEssParamterForm.setInfoId(infoId);
        log.info("infoId:"+infoId);
        System.out.println("infoId:"+infoId);
        String s = "";
        try {
             log.info("回调开始");
             s = methodEx.attCallback(zyEssParamterForm);
             log.info("回调结果"+s);
        } catch (Exception_Exception e) {
            e.printStackTrace();
        }
//        if (!"200".equals(JSONObject.parseObject(s).getString("code"))){
//            //签章上传文件
//            result.put("code","0009");
//            result.put("msg","OA通知失败");
//            return result.toJSONString();
//        }
        result.put("url",url);
        return result.toJSONString();
    }
}
